package com.example.manager.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.manager.entity.Gender;
import com.example.manager.entity.Student;
import com.example.manager.repository.StudentRepository;

@Service
@Transactional
public class StudentServiceImpl implements StudentService {
	
	@Autowired
	private StudentRepository studentRepository;
	
	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Student> getAllStudent() {
		List<Student> stu = studentRepository.findAll();
		
		return stu;
	}

	@Override
	public Student getStudentBySid(String sid) {
		
		Student stu = studentRepository.findById(sid).get();
		return stu;
	}

	@Override
	public String editStudent(Student stu) {
		String sid = stu.getSid();
		Student stu2 = studentRepository.getOne(sid);
		String name = stu.getName();
		String password = stu.getPassword();
		Gender gender = stu.getGender();
		Date birthday = stu.getBirthday();
	
		if((sid == null||sid.length()==0)||(name==null||name.length()==0)||(password==null||password.length()==0)||(gender==null)||(birthday==null)) {
			return "imcomplete info";
		}
		
		
		stu2.setName(stu.getName());
		
		
		stu2.setPassword(stu.getPassword());
		
	
		stu2.setGender(stu.getGender());
	
		
		stu2.setBirthday(stu.getBirthday());
	
		
		studentRepository.save(stu2);
		return "success";
	
		
	}
	
	@Override
	public String addStudent(Student stu) {
		String sid = stu.getSid();
		String name = stu.getName();
		String password = stu.getPassword();
		Gender gender = stu.getGender();
		Date birthday = stu.getBirthday();
		if((sid == null||sid.length()==0)||(name==null||name.length()==0)||(password==null||password.length()==0)||(gender==null)||(birthday==null)) {
			return "imcomplete info";
		}
		if(studentRepository.existsById(sid)){
			return "id exsists";
		}else {
		
			
			studentRepository.save(stu);
			return "success";
			
		}
		
	}

	@Override
	public String deleteStudent(String sid) {
		if(studentRepository.existsById(sid)) {
			studentRepository.deleteById(sid);
			return "success";
		}else {
			return "fail";
		}
	}

}
